import React, { useState, useRef, useEffect } from 'react';
import ReactMarkdown from 'react-markdown';
import { 
  generateScriptOutline, 
  generateCompleteScript, 
  saveCompleteScript,
  generateScriptFragment,
  searchProductInfo
} from '../../services/api';
import { Pen, Save, Feather, Plus, X, Zap, Edit, Eye } from 'lucide-react';

interface MarkdownEditorProps {
  content: string;
  title: string;
  onContentChange: (content: string) => void;
  onTitleChange: (title: string) => void;
  showOutlineButton: boolean;
  showCompleteButton: boolean;
  showSaveButton: boolean;
  userId: number;
  productDesc: string;
  scriptOutline: string;
  selectedScriptId: number | null;
  selectedScriptIds?: number[];
  onOutlineGenerated: (outline: string) => void;
  onCompleteScriptGenerated: (script: string) => void;
  referenceScript?: {
    title: string;
    content: string;
    version: number;
  };
}

const MarkdownEditor: React.FC<MarkdownEditorProps> = ({
  content,
  title,
  onContentChange,
  onTitleChange,
  showOutlineButton,
  showCompleteButton,
  showSaveButton,
  userId,
  productDesc,
  scriptOutline,
  selectedScriptId,
  selectedScriptIds = [],
  onOutlineGenerated,
  onCompleteScriptGenerated,
  referenceScript
}) => {
  const [isEditing, setIsEditing] = useState(true);
  const [isGenerating, setIsGenerating] = useState(false);
  const [showFragmentInput, setShowFragmentInput] = useState(false);
  const [fragmentInputPosition, setFragmentInputPosition] = useState({ x: 0, y: 0 });
  const [fragmentRequest, setFragmentRequest] = useState('');
  const [selectedText, setSelectedText] = useState('');
  const [originalOutline, setOriginalOutline] = useState<string>('');
  const editorRef = useRef<HTMLTextAreaElement>(null);

  const [showFloatingBall, setShowFloatingBall] = useState(false);
  const [floatingBallPosition, setFloatingBallPosition] = useState({ x: 0, y: 0 });
  const [floatingBallHovered, setFloatingBallHovered] = useState(false);
  const [floatingBallExpanded, setFloatingBallExpanded] = useState(false);
  const [isFragmentGenerating, setIsFragmentGenerating] = useState(false);
  const [showSuccessToast, setShowSuccessToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  useEffect(() => {
    const handleSelectionChange = () => {
      if (document.activeElement === editorRef.current) {
        const selection = window.getSelection();
        if (selection && selection.toString()) {
          const range = selection.getRangeAt(0);
          const rect = range.getBoundingClientRect();
          setSelectedText(selection.toString());
          setFloatingBallPosition({
            x: rect.right,
            y: rect.bottom
          });
          setShowFloatingBall(true);
          setShowFragmentInput(false);
          setFloatingBallExpanded(false);
        } else {
          setShowFloatingBall(false);
          setShowFragmentInput(false);
        }
      }
    };

    document.addEventListener('selectionchange', handleSelectionChange);
    return () => {
      document.removeEventListener('selectionchange', handleSelectionChange);
    };
  }, []);
  
  const showToast = (message: string) => {
    setToastMessage(message);
    setShowSuccessToast(true);
    setTimeout(() => {
      setShowSuccessToast(false);
    }, 3000);
  };

  const showCustomAlert = (title: string, message: string, type: 'info' | 'error' | 'success' = 'info') => {
    const alertElement = document.createElement('div');
    alertElement.className = 'fixed inset-0 flex items-center justify-center z-50';
    
    const colorClass = type === 'error' ? 'text-ink-red' : type === 'success' ? 'text-ink-green' : 'text-ink';
    
    alertElement.innerHTML = `
      <div class="fixed inset-0 bg-ink/20 backdrop-blur-sm" onclick="this.parentElement.remove()"></div>
      <div class="glass p-6 rounded-lg shadow-float animate-float-in max-w-md">
        <h3 class="font-playfair text-lg ${colorClass} mb-4">${title}</h3>
        <p class="font-inter text-ink mb-6">${message}</p>
        <div class="flex justify-end">
          <button class="ink-btn px-4 py-2 rounded-md text-sm" onclick="this.closest('.fixed').remove()">
            确定
          </button>
        </div>
      </div>
    `;
    document.body.appendChild(alertElement);
  };

  const handleGenerateOutline = async () => {
    if (!productDesc) {
      showCustomAlert('提示', '请先上传产品资料', 'info');
      return;
    }

    setIsGenerating(true);
    try {
      const referenceIds = selectedScriptIds.length > 0 ? selectedScriptIds : (selectedScriptId ? [selectedScriptId] : undefined);
      const response = await generateScriptOutline(userId, productDesc, referenceIds);
      
      if (response.data.code === 200) {
        const outlineData = response.data.data;
        let outlineMarkdown = '';
        
        if (outlineData.status === 'success' && outlineData.content && outlineData.content.length > 0) {
          outlineData.content.forEach((section: { title: string; description: string }) => {
            outlineMarkdown += `## ${section.title}\n\n${section.description}\n\n`;
          });
        } else if (outlineData.sections && outlineData.sections.length > 0) {
          outlineData.sections.forEach((section: { title: string; content: string }) => {
            outlineMarkdown += `## ${section.title}\n\n${section.content}\n\n`;
          });
        } else {
          outlineMarkdown = JSON.stringify(outlineData);
        }
        
        onOutlineGenerated(outlineMarkdown);
        showToast('大纲生成成功');
      } else {
        showCustomAlert('生成失败', `生成大纲失败: ${response.data.msg}`, 'error');
      }
    } catch (error) {
      console.error('Error generating outline:', error);
      showCustomAlert('生成失败', '生成大纲失败，请稍后重试', 'error');
    } finally {
      setIsGenerating(false);
    }
  };

  const handleGenerateCompleteScript = async () => {
    if (!productDesc || !scriptOutline) {
      showCustomAlert('提示', '请先生成话术大纲', 'info');
      return;
    }

    setOriginalOutline(scriptOutline);

    setIsGenerating(true);
    try {
      let productDescData = productDesc;
      try {
        const productSearchResponse = await searchProductInfo(userId, productDesc);
        if (productSearchResponse.data.code === 200 && productSearchResponse.data.data) {
          productDescData = productSearchResponse.data.data;
        }
      } catch (error) {
        console.error('Error fetching product info:', error);
      }
      
      let outlineObject;
      try {
        const sections = [];
        const regex = /## (.*?)\n\n(.*?)(?=\n\n## |$)/gs;
        let match;
        
        while ((match = regex.exec(scriptOutline)) !== null) {
          sections.push({
            title: match[1].trim(),
            description: match[2].trim()
          });
        }
        
        if (sections.length > 0) {
          outlineObject = sections;
        } else {
          try {
            outlineObject = JSON.parse(scriptOutline);
          } catch (e) {
            outlineObject = scriptOutline;
          }
        }
      } catch (error) {
        console.error('Error parsing outline:', error);
        outlineObject = scriptOutline;
      }
      
      const outlineJsonString = typeof outlineObject === 'string' ? 
        outlineObject : JSON.stringify(outlineObject);
      
      const referenceIds = selectedScriptIds.length > 0 ? selectedScriptIds : (selectedScriptId ? [selectedScriptId] : []);
      const response = await generateCompleteScript(userId, productDescData, outlineJsonString, referenceIds);
      
      if (response.data.code === 200) {
        const scriptData = response.data.data;
        let scriptContent = '';
        
        if (scriptData.status === 'success' && scriptData.content && scriptData.content.length > 0) {
          scriptData.content.forEach((section: { title: string; content: string }) => {
            scriptContent += `## ${section.title}\n\n${section.content}\n\n`;
          });
        } else if (scriptData.content) {
          scriptContent = scriptData.content;
        } else if (scriptData.sections && scriptData.sections.length > 0) {
          scriptData.sections.forEach((section: { title: string; content: string }) => {
            scriptContent += `## ${section.title}\n\n${section.content}\n\n`;
          });
        } else {
          scriptContent = JSON.stringify(scriptData);
        }
        
        onCompleteScriptGenerated(scriptContent);
        showToast('完整话术生成成功');
      } else {
        showCustomAlert('生成失败', `生成完整话术失败: ${response.data.msg}`, 'error');
      }
    } catch (error) {
      console.error('Error generating complete script:', error);
      showCustomAlert('生成失败', '生成完整话术失败，请稍后重试', 'error');
    } finally {
      setIsGenerating(false);
    }
  };

  const handleSaveScript = async () => {
    if (!title || !content) {
      showCustomAlert('提示', '请输入标题和内容', 'info');
      return;
    }

    try {
      const response = await saveCompleteScript(userId, title, content);
      
      if (response.data.code === 200) {
        showToast('保存成功');
      } else {
        showCustomAlert('保存失败', `${response.data.msg}`, 'error');
      }
    } catch (error) {
      console.error('Error saving script:', error);
      showCustomAlert('保存失败', '请稍后重试', 'error');
    }
  };

  const handleGenerateFragment = async () => {
    if (!selectedText) {
      showCustomAlert('提示', '请先选择文本', 'info');
      return;
    }

    setIsGenerating(true);
    setIsFragmentGenerating(true);
    try {
      let productDescData = productDesc;
      try {
        const productSearchResponse = await searchProductInfo(userId, productDesc);
        if (productSearchResponse.data.code === 200 && productSearchResponse.data.data) {
          productDescData = productSearchResponse.data.data;
        }
      } catch (error) {
        console.error('Error fetching product info:', error);
      }
      
      const outlineToUse = originalOutline || scriptOutline;
      
      let outlineObject;
      try {
        const sections = [];
        const regex = /## (.*?)\n\n(.*?)(?=\n\n## |$)/gs;
        let match;
        
        while ((match = regex.exec(outlineToUse)) !== null) {
          sections.push({
            title: match[1].trim(),
            description: match[2].trim()
          });
        }
        
        if (sections.length > 0) {
          outlineObject = sections;
        } else {
          try {
            outlineObject = JSON.parse(outlineToUse);
          } catch (e) {
            outlineObject = outlineToUse;
          }
        }
      } catch (error) {
        console.error('Error parsing outline:', error);
        outlineObject = outlineToUse;
      }
      
      const outlineJsonString = typeof outlineObject === 'string' ? 
        outlineObject : JSON.stringify(outlineObject);
      
      const referenceIds = selectedScriptIds.length > 0 ? selectedScriptIds : (selectedScriptId ? [selectedScriptId] : []);
      const response = await generateScriptFragment(
        userId, 
        productDescData, 
        outlineJsonString, 
        selectedText, 
        content, // Pass the current content
        fragmentRequest, 
        referenceIds
      );
      
      if (response.data.code === 200) {
        const fragmentData = response.data.data;
        let fragment = '';
        
        if (fragmentData.status === 'success' && fragmentData.content) {
          fragment = fragmentData.content;
        } else if (fragmentData.content) {
          fragment = fragmentData.content;
        } else {
          fragment = JSON.stringify(fragmentData);
        }
        
        const newContent = content.replace(selectedText, fragment);
        onContentChange(newContent);
        showToast('片段话术生成成功');
      } else {
        showCustomAlert('生成失败', `生成片段话术失败: ${response.data.msg}`, 'error');
      }
    } catch (error) {
      console.error('Error generating fragment:', error);
      showCustomAlert('生成失败', '生成片段话术失败，请稍后重试', 'error');
    } finally {
      setIsGenerating(false);
      setIsFragmentGenerating(false);
      setShowFragmentInput(false);
      setFragmentRequest('');
    }
  };

  const handleFloatingBallClick = () => {
    setFloatingBallExpanded(true);
    setTimeout(() => {
      setShowFloatingBall(false);
      setShowFragmentInput(true);
      setFragmentInputPosition(floatingBallPosition);
      setFloatingBallExpanded(false);
    }, 300);
  };

  return (
    <div className="relative">
      {/* Reference Script Preview */}
      {referenceScript && (
        <div className="mb-6 bg-paper rounded-lg shadow-medium overflow-hidden">
          <div className="p-4 border-b border-ink/10 flex justify-between items-center">
            <div>
              <h3 className="text-subtitle font-montserrat text-ink">{referenceScript.title}</h3>
              <p className="text-body font-inter text-ink/70 mt-1">
                版本: <span className="text-ink-blue font-medium">{referenceScript.version}</span>
              </p>
            </div>
          </div>
          <div className="p-6 prose max-w-none font-inter text-ink">
            <div className="whitespace-pre-wrap bg-paper border border-ink/10 rounded-lg p-6">
              {referenceScript.content}
            </div>
          </div>
        </div>
      )}
      
      {/* Title input */}
      {(showCompleteButton || showSaveButton) && (
        <div className="mb-4">
          <input
            type="text"
            value={title}
            onChange={(e) => onTitleChange(e.target.value)}
            placeholder="请输入标题"
            className="w-full px-4 py-3 bg-paper border border-ink/10 rounded-lg font-montserrat text-ink text-title focus:ring-2 focus:ring-ink-blue/20 focus:border-ink-blue/30 transition-all duration-200"
          />
        </div>
      )}
      
      {/* Editor/Preview toggle */}
      <div className="flex justify-between mb-3">
        <div className="flex space-x-2">
          <button
            onClick={() => setIsEditing(true)}
            className={`px-4 py-2 rounded-lg font-inter text-sm transition-all duration-200 flex items-center space-x-2 ${
              isEditing 
                ? 'bg-ink text-paper shadow-light' 
                : 'bg-paper text-ink hover:bg-ink/5'
            }`}
          >
            <Edit size={16} />
            <span>编辑</span>
          </button>
          <button
            onClick={() => setIsEditing(false)}
            className={`px-4 py-2 rounded-lg font-inter text-sm transition-all duration-200 flex items-center space-x-2 ${
              !isEditing 
                ? 'bg-ink text-paper shadow-light' 
                : 'bg-paper text-ink hover:bg-ink/5'
            }`}
          >
            <Eye size={16} />
            <span>预览</span>
          </button>
        </div>
        
        <div className="flex space-x-3">
          {showCompleteButton && (
            <button
              onClick={handleGenerateCompleteScript}
              disabled={isGenerating}
              className="px-4 py-2 flex items-center space-x-2 font-inter text-sm rounded-lg bg-ink-red text-paper shadow-light hover:bg-ink-red/90 transition-all duration-200 disabled:opacity-50"
            >
              {isGenerating ? (
                <span className="flex items-center">
                  <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-paper" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  生成中...
                </span>
              ) : (
                <>
                  <Zap size={18} />
                  <span>生成完整话术</span>
                </>
              )}
            </button>
          )}
          
          {showSaveButton && (
            <button
              onClick={handleSaveScript}
              className="px-4 py-2 flex items-center space-x-2 font-inter text-sm rounded-lg bg-ink-green text-paper shadow-light hover:bg-ink-green/90 transition-all duration-200"
            >
              <Save size={18} />
              <span>保存话术</span>
            </button>
          )}
        </div>
      </div>
      
      {/* Editor/Preview content */}
      <div className="min-h-[400px] bg-paper rounded-lg shadow-medium overflow-hidden relative">
        {/* Light paper lines in the background */}
        <div className="absolute inset-0 pointer-events-none" 
          style={{
            backgroundImage: 'repeating-linear-gradient(transparent, transparent 31px, rgba(58, 50, 56, 0.05) 31px, rgba(58, 50, 56, 0.05) 32px)',
            backgroundSize: '100% 32px',
            backgroundPosition: '0 10px'
          }}>
        </div>
        
        {isEditing ? (
          <textarea
            ref={editorRef}
            value={content}
            onChange={(e) => onContentChange(e.target.value)}
            className="w-full h-full min-h-[400px] p-6 bg-transparent font-inter text-ink text-body focus:outline-none resize-none relative z-10"
            placeholder="在此输入内容..."
            style={{
              caretColor: '#6E9CAA'
            }}
          />
        ) : (
          <div className="p-6 prose prose-headings:text-left prose-p:text-left prose-ul:text-left prose-ol:text-left max-w-none h-full min-h-[400px] overflow-y-auto relative z-10 prose-headings:font-montserrat prose-p:font-inter prose-strong:font-work-sans prose-em:font-work-sans">
            <ReactMarkdown>{content}</ReactMarkdown>
          </div>
        )}
      </div>
      
      {/* Generate outline button */}
      {showOutlineButton && content.trim() === '' && (
        <div className="fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-50">
          <button
            onClick={handleGenerateOutline}
            disabled={isGenerating}
            className="px-8 py-4 text-ink rounded-lg shadow-medium hover:shadow-deep transform hover:scale-[1.02] transition-all duration-200 flex items-center space-x-2 disabled:opacity-50 bg-paper"
          >
            {isGenerating ? (
              <span className="flex items-center">
                <svg className="animate-spin mr-3 h-5 w-5 text-ink-blue" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span className="font-montserrat text-subtitle">生成中...</span>
              </span>
            ) : (
              <>
                <Pen className="h-6 w-6 mr-2 text-ink-blue" />
                <span className="font-montserrat text-subtitle">生成话术大纲</span>
              </>
            )}
          </button>
        </div>
      )}
      
      {/* Floating ball UI */}
      {showFloatingBall && (
        <div
          className={`fixed z-50 ${floatingBallExpanded ? 'w-14 h-14' : 'w-10 h-10'} rounded-full flex items-center justify-center cursor-pointer shadow-medium hover:shadow-deep transform transition-all duration-200`}
          style={{
            left: `${floatingBallPosition.x}px`,
            top: `${floatingBallPosition.y + 10}px`,
            background: '#6E9CAA',
            transform: floatingBallExpanded ? 'scale(1.1)' : 'scale(1)',
          }}
          onClick={handleFloatingBallClick}
          onMouseEnter={() => setFloatingBallHovered(true)}
          onMouseLeave={() => setFloatingBallHovered(false)}
        >
          <Plus 
            className={`text-paper transition-all duration-200 ${floatingBallHovered ? 'rotate-45' : ''}`} 
            size={floatingBallExpanded ? 24 : 20} 
          />
        </div>
      )}
      
      {/* Success Toast */}
      {showSuccessToast && (
        <div className="fixed bottom-8 right-8 z-50 px-6 py-4 rounded-lg shadow-medium animate-float-in flex items-center space-x-3 bg-ink-green text-paper"
        >
          <div className="w-6 h-6 bg-paper rounded-full flex items-center justify-center">
            <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-ink-green" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <span className="font-inter text-body">{toastMessage}</span>
        </div>
      )}
      
      {/* Fragment input floating UI */}
      {showFragmentInput && (
        <div
          className="absolute z-10 rounded-lg shadow-deep p-5 w-80 animate-float-in bg-paper"
          style={{
            left: `${fragmentInputPosition.x}px`,
            top: `${fragmentInputPosition.y + 10}px`,
          }}
        >
          <div className="flex justify-between items-center mb-2">
            <h3 className="font-montserrat text-ink text-subtitle">片段生成</h3>
            <button 
              onClick={() => setShowFragmentInput(false)}
              className="w-6 h-6 rounded-full flex items-center justify-center text-ink/70 hover:bg-ink/5 transition-colors"
            >
              <X size={16} />
            </button>
          </div>
          <textarea
            value={fragmentRequest}
            onChange={(e) => setFragmentRequest(e.target.value)}
            className="w-full p-3 bg-paper border border-ink/10 rounded-lg mb-3 font-inter text-ink text-body focus:ring-2 focus:ring-ink-blue/20 focus:border-ink-blue/30 transition-all duration-200 resize-none"
            placeholder="输入生成要求（可选）"
            rows={2}
            autoFocus
          />
          <div className="flex justify-end">
            <button
              onClick={handleGenerateFragment}
              disabled={isGenerating || isFragmentGenerating}
              className="px-4 py-2 flex items-center space-x-2 font-inter text-sm rounded-lg bg-ink-blue text-paper shadow-light hover:bg-ink-blue/90 transition-all duration-200 disabled:opacity-50"
            >
              {isFragmentGenerating ? (
                <span className="flex items-center">
                  <svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-paper" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  生成中...
                </span>
              ) : (
                <>
                  <Feather size={18} />
                  <span>生成片段</span>
                </>
              )}
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default MarkdownEditor;
